<template>
  <div>
    <h2>推文管理</h2>
    <el-table :data="tweetData" style="width: 100%" >
      <el-table-column prop="tname" label="推文名称" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="createtime" label="发布时间" />
      <el-table-column prop="updatetime" label="最后修改时间" />
      <el-table-column label="操作" fixed="right" width="250">
        <template #default="scope">
          <el-button size="small" @click="handleTweet(scope.row, 'preview')" type="success">预览</el-button>
          <el-button size="small" @click="showEditDialog(scope.row)" type="primary">修改</el-button>
          <el-popconfirm
            title="确定要删除此推文吗？"
            @confirm="() => handleDelete(scope.row.tid)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 预览模态窗口 -->
    <el-dialog v-model="previewDialogVisible"  width="30%">
      <el-form :model="previewData" label-width="100px">
        <h1>{{ previewData.tname }}</h1><br><hr>
        <el-form-item label="活动类型:">
          <span>{{ previewData.type }}</span>
        </el-form-item>
        <el-form-item label="活动地点:">
          <span>{{ previewData.area }}</span>
        </el-form-item>
        <el-form-item label="活动介绍:">
          <span>{{ previewData.text }}</span>
        </el-form-item>
        <hr>
        <el-form-item label="发布时间:">
          <span>{{ previewData.createtime }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑模态窗口 -->
    <el-dialog v-model="editDialogVisible" title="编辑推文" width="30%" @close="resetEditForm">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="150px">
        <el-form-item label="推文标题" prop="tname">
          <el-input v-model="editForm.tname"></el-input>
        </el-form-item>

        <el-form-item label="活动时间" prop="atime">
              <el-date-picker
                  v-model="editForm.atime"
                  type="datetime"
                  placeholder="选择活动时间"
                  clearable="clearable"
                  style="width: 100%;"
              ></el-date-picker>
        </el-form-item>

        <el-form-item label="活动类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择活动类型">
            <el-option label="创造能力" value="创造能力"></el-option>
            <el-option label="文体能力" value="文体能力"></el-option>
            <el-option label="社会实践能力" value="社会实践能力"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动地点" prop="area">
          <el-input v-model="editForm.area"></el-input>
        </el-form-item>

        <el-form-item label="是否需要提前报名" prop="take">
          <el-checkbox v-model="editForm.take">是</el-checkbox>
        </el-form-item>

        <hr><br>
		  
		  <el-form-item label="活动介绍:" prop="text">
        <el-input
          type="textarea"
          :rows="8"
          v-model="editForm.text"
          @input="updateTextCount"
          placeholder="请输入活动介绍"
        ></el-input>
        <span class="char-count" :class="{ green: textCount > 0 }">{{ textCount }} </span>
		  </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEditedTweet">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex';
import axiosInstance from '@/plugins/Axios.js';
import { ElMessage } from 'element-plus';

const store = useStore();

// 响应式引用
const tweetData = ref([]);
const previewDialogVisible = ref(false);
const previewData = ref({});
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = ref({});
let textCount = ref(0);

// 获取签到表数据
const fetchTweet = async () => {
  try {
    const did = store.getters.CurrentUser.did;
    if (!did) {
      console.warn('当前用户未登录或登录信息尚未准备好');
      return;
    }
    const response = await axiosInstance.selectArticlesByDid(did);
    tweetData.value = response.data;
  } catch (error) {
    console.error('获取推文数据失败时出错:', error);
    ElMessage.error('获取推文数据失败');
  }
};

// 页面加载时获取所有数据
onMounted(() => {
  fetchTweet();
});

// 操作函数
const handleTweet = (row, action) => {
  if (action === 'preview') {
    preview(row);
  }
};

// 查看推文
const preview = async (row) => {
  try {
    const tid = row.tid;
    const response = await axiosInstance.selectArticle(tid);
    previewData.value = response.data;
    previewDialogVisible.value = true;
  } catch (error) {
    console.error('获取推文详情失败:', error);
    ElMessage.error('获取推文详情失败');
  }
};

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    const tid = row.tid;
    const response = await axiosInstance.selectArticle(tid);
    editForm.value = response.data;
    editDialogVisible.value = true;
    // 确保take属性存在并设置正确的值
    if (response.data.take === undefined) {
      editForm.value.take = false; // 如果没有take属性，则默认为false
    } else {
      editForm.value.take = response.data.take; // 设置take的值
    }
  } catch (error) {
    console.error('获取推文详情失败:', error);
    ElMessage.error('获取推文详情失败');
  }
};

// 重置编辑表单
const resetEditForm = () => {
  editFormRef.value.resetFields();
  editForm.value.take = false; // 重置take为false
};

const updateTextCount = () => {
  textCount.value = editForm.value.text.length;
};

// 保存编辑的推文
const saveEditedTweet = async () => {
  try {
    const response = await axiosInstance.updateArticle(editForm.value);
    ElMessage.success('推文已成功更新');
    fetchTweet(); // 刷新列表
    editDialogVisible.value = false; // 关闭编辑对话框
  } catch (error) {
    console.error('更新推文失败:', error);
    ElMessage.error('更新推文失败');
  }
};

// 删除推文
const handleDelete = async (tid) => {
  try {
    await axiosInstance.deleteArticle(tid);
    ElMessage.success('推文删除成功');
    fetchTweet();
  } catch (error) {
    console.error('删除推文失败:', error);
    ElMessage.error('删除推文失败');
  }
};
</script>

<style scoped>
.char-count {
  position: absolute;
  bottom: 6px;
  right: 6px;
  font-size: 12px;
}

.green {
  color: green;
}
</style>